package com.atguigu.springcloud.service.impl;

import cn.hutool.core.util.IdUtil;
import com.atguigu.springcloud.dao.PaymentDao;
import com.atguigu.springcloud.entities.Payment;
import com.atguigu.springcloud.service.PaymentService;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;

import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;


@Service
public class PaymentServiceImpl implements PaymentService
{

    @Resource
    private PaymentDao paymentDao;


    @Override
    public int addPayment(Payment payment) {
      return   paymentDao.addPayment(payment);

    }

    @Override
    public Payment getPaymentById(long id) {
        return paymentDao.getPaymentById(id);
    }


    public String paymentInfo_ok(Integer id){
        /**
         * 正常访问 没我有问题的方法
         */
        return  "线程池： "+Thread.currentThread().getName()+" PaymentInfo_ok,id: "+id;

    }

    @HystrixCommand(fallbackMethod = "paymentInfo_TimeoutHandler",commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "5000")
    })
    public String paymentInfo_timeOut(Integer id){

        /**
         * 故意延迟5秒 是服务器爆出 超时错误
         */
        int time =3;
        try {
            TimeUnit.SECONDS.sleep(time);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
//        int i= time/0;
        return  "线程池： "+Thread.currentThread().getName()+" PaymentInfo_timeOut,id: "+id;
    }

    public String paymentInfo_TimeoutHandler(Integer id){

        return  "线程池： "+Thread.currentThread().getName()+" 8001系统繁忙或者出错请稍后再试,id: "+id;
    }

    //===================服务熔断

    @HystrixCommand(fallbackMethod = "paymentCircuitBreaker_fallback",commandProperties = {
            @HystrixProperty(name = "circuitBreaker.enabled",value = "true"),//是否开启断路器
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "10"),//请求次数
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds",value ="10000"),//时间窗口期
            @HystrixProperty(name="circuitBreaker.errorThresholdPercentage",value = "60"),//失败率达到多少后跳闸 熔断
    })
    public String paymentCircuitBreaker(Integer id){
        if (id<0){
            throw new RuntimeException(" id 不能为负数");
        }
        String uuid = IdUtil.simpleUUID();

        return Thread.currentThread().getName()+"\t"+"调用成功，流水号"+uuid;
    }


    public String paymentCircuitBreaker_fallback(Integer id){

        return "请稍后再试  id:"+id;
    }




}
